import {ref,reactive} from 'vue'
import axios from 'axios'

// 连接
const link_btn = reactive({
    esurl:"",
    type:'primary',
    txt:'连接',
    link:()=>{
        axios.get(`${link_btn.esurl}/_cat/indices?format=json`).then(Response=>{ // 获取索引列表
            let indexlist = Response.data
            link_btn.txt="成功"
            link_btn.type="success";
            localStorage.esurl = link_btn.esurl
            let esindex = []
            for (const iterator of indexlist) {
                if(iterator.rep=="1"){
                    esindex.push({
                        value:iterator.index,
                        label:iterator.index
                    })
                }
            }
            _select.esindex = esindex
    
        }).catch(error => {
            link_btn.txt="失败"
            link_btn.type="danger";
        })
    }
})

// 列表
const _collapse = reactive({
    total:0, // 总数
    current:1, // 当前页
    activeNames:[],
    data:[{_source:''}]
})

// 索引与搜索
const _select = reactive({
    value:'',
    esindex:[
        {
            value:'',
            label:''
        }
    ],
    searchbtn:()=>{
        _select.search(1)
    },
    search:(val)=>{
        _collapse.current = val?val:1
        axios.get(`${link_btn.esurl}/${_select.value}/_search?from=${_collapse.current}`)
        .then(Response=>{
            let data = Response.data
            localStorage.esindex = _select.value
            _collapse.total = data.hits.total.value
            _collapse.data = data.hits.hits
            console.log(data);
        })

    }
})

// 多选框组
const checkbox_group = reactive({
    checkList:[],
    change:()=>{
        console.log(checkbox_group.checkList);
    }
})

function gotourl(data){
    console.log(data)
    localStorage.data = JSON.stringify(data,null,2)   

}



if(localStorage.esurl){
    link_btn.esurl = localStorage.esurl
    link_btn.link()
}
if(localStorage.esindex){
    _select.value = localStorage.esindex
    _select.search()
}

// 重置
const clear = ()=>{
    localStorage.clear();
    link_btn.esurl = ""
    link_btn.type = 'primary'
    link_btn.txt = '连接'   
    _collapse.total = 0, // 总数
    _collapse.current = 1, // 当前页
    _collapse.activeNames = [],
    _collapse.data = [{_source:''}]


    _select.value = ''
    _select.esindex = [{value:'',label:''}]
    
    checkbox_group.checkList = []

}


export {link_btn,_select,_collapse,gotourl,checkbox_group,clear}